import 'babel-polyfill';
import Vue from 'vue';
import VueLazyload from 'vue-lazyload';
import EleForm from 'vue-ele-form';
import EleFormDynamic from '@/components/FormDynamic';
import EleFormUploadFile from '@/components/Upload/eleFormUploadFile';
import EleFormUploadPlusFile from '@/components/Upload/eleFormUploadPlusFile';
import EleFormCustomSelect from '@/components/Dialog/custom-select';
import EleFormInputWithTips from '@/components/CheckoutMenu/input-with-tips';
import EleFormSelectWithTips from '@/components/CheckoutMenu/select-with-tips';
import VueQuillEditor, { Quill } from 'vue-quill-editor';
import EleFormQuillEdit from '@/components/Editor/quill';
import EleSpace from '@/components/Interval';
import imgHostDirectives from './directives/imgHost';
import 'normalize.css/normalize.css'; // CSS resets
import App from './App.vue';
import router from '@/router';
import store from '@/store';
import './plugins/element.js';
import '@/styles/index.scss'; // global  css
import '@/styles/mobile.scss'; // Add mobile-specific styles
import '@/icons'; // icon
import '@/permission'; // permission control
import Area from '@/components/Area';
import Images from '@/components/Images';
import DatePicker from '@/components/DatePicker';
import Empty from '@/components/Empty';
import { parseTime } from '@/utils/utils';
import * as filters from '@/utils/filters';
import VueClipboard from 'vue-clipboard2';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { installMobileDetection } from '@/utils/mobile';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import locale from 'element-ui/lib/locale/lang/zh-CN'; // lang i18n
import InfiniteScroll from 'element-ui/lib/infinite-scroll';
const sizeStyle = Quill.import('attributors/style/size');
sizeStyle.whitelist = ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '30px', '32px', '36px', '40px', '44px', '48px', '52px', '56px', '60px', '64px', '68px', '72px', '76px', '80px', '84px', '88px'];
Quill.register(sizeStyle, true);

Vue.config.productionTip = false;
function handler (el) {
    let num = 0;
    const interval = window.setInterval(() => {
        if (el.currentSrc || num === 100) {
            // el.removeAttribute('style');
            el.style.opacity = 1;
            // el.style.padding = 'inherit';
            if (!el.classList.contains('product-image-hover')) {
                el.classList.add('zoom-leave-leave');
            }
            window.clearInterval(interval);
        }
        num++;
    }, 200);
}

// 判断webp
const canUseWebp =
    document
        .createElement('canvas')
        .toDataURL('image/webp')
        .indexOf('data:image/webp') === 0;
let webp = '';
if (canUseWebp) {
    webp = '/format,webp';
}

const compressImg = (imgUrl, el) => {
    // 如果不是oss 或者已经压缩过的图片直接返回
    // if (imgUrl.includes('aliyuncs.com') || imgUrl.indexOf('blob') === 0 || imgUrl.includes('x-oss-process=')) {
    //     return imgUrl;
    // }
    if (imgUrl.includes('no-resize') || !el) {
        return imgUrl;
    }
    const type = el.getAttribute('data');
    // 获取显示设备 pixelRatio
    // const pixelRatio = window.devicePixelRatio;
    // const elWidth = el.width * pixelRatio;
    // const elHeight = el.height * pixelRatio;
    const elWidth = el.width;
    const elHeight = el.height;
    let resize = '/resize,m_fill';
    if (type === 'product') {
        resize = '/resize';
    }
    if (elWidth) {
        resize += type === 'product' ? `,l_${elWidth * 2}` : `,w_${elWidth * 2},h_${Math.ceil(elWidth * 2.5)}`;
    }
    // if (elHeight) {
    //     resize += `,h_${elWidth * 1.25}`;
    // }
    if (!elWidth && !elHeight) {
        resize = '';
    }
    return type === 'product' ? `${imgUrl}?x-oss-process=image${resize}/auto-orient,1/bright,-1${webp}` : `${imgUrl}?x-oss-process=image${resize}/auto-orient,1/bright,-1${webp}`;
};
Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key]);
});
Vue.use(Area);
Vue.use(Images);
Vue.use(DatePicker);
Vue.use(Empty);
Vue.use(EleForm, {
    dynamic: {
        delimiter: '/' // 所有的 dynamic 都会有 delimiter = '/' 的属性值
    }
});
Vue.use(VueClipboard);
Vue.use(VueQuillEditor, {
    modules: {
        toolbar: [
            ['bold', 'italic'],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'size': ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '30px', '32px', '36px', '40px', '44px', '48px', '52px', '56px', '60px', '64px', '68px', '72px', '76px', '80px', '84px', '88px'] }],
            ['clean']
        ]
    }
});
Vue.directive('loadmore', {
    bind (el, binding) {
        setTimeout(() => {
            const selectWrap = el.querySelector('.el-table__body-wrapper');
            selectWrap.addEventListener('scroll', function () {
                if (this.scrollHeight - this.scrollTop <= this.clientHeight + 70) {
                    binding.value();
                }
            });
        }, 300);
    },
    unbind: (el) => {
        const selectWrap = el.querySelector('.el-table__body-wrapper');
        selectWrap.$listener && selectWrap.removeEventListener('scroll', selectWrap.$listener);
    }
});
Vue.directive('watermark', (el, binding) => {
    const addWaterMarker = (text, time, el) => {
        let canvas = document.createElement('canvas');
        canvas.width = 400;
        canvas.height = 200;
        let cans = canvas.getContext('2d');
        cans.rotate((-20 * Math.PI) / 180); // 旋转弧度
        cans.font = '14px Microsoft JhengHei'; // 字体
        cans.fillStyle = 'rgba(0, 0, 0, 0.1)'; // 字体填充颜色
        cans.textAlign = 'center'; // 对齐方式
        cans.textBaseline = 'Middle'; // 基线
        cans.fillText(text, canvas.width / 3, canvas.height / 2); // 被填充的文本
        cans.fillText(parseTime(time), canvas.width / 3, 130); // 被填充的文本
        el.style.backgroundImage = `url(${canvas.toDataURL('image/png')})`; // 插入背景图
    };
    const { text, time } = binding.value;
    addWaterMarker(text, time, el);
});

Vue.use(imgHostDirectives);
Vue.use(VueLazyload, {
    preLoad: 1, // 提前加载高度
    error: require('@/assets/images/bg-grey.png'), // 图片加载失败后
    loading: require('@/assets/images/bg-grey.png'), // 图片正在加载时
    attempt: 3, // 加载错误后最大尝试次数
    observer: true,
    observerOptions: {
        rootMargin: '0px',
        threshold: 0.1
    },
    adapter: {
        loaded ({ bindType, el }) {
            if (el.nodeName === 'IMG') {
                handler(el);
            }
        },
        loading (listener, Init) {
            if (!listener.el.style.paddingTop) {
                let padding = 100;
                const ratio = listener.el.getAttribute('ratio');
                if (ratio) {
                    padding = ratio;
                } else if (listener.el.getAttribute('width') && listener.el.getAttribute('height')) {
                    padding = (listener.el.getAttribute('height') / listener.el.getAttribute('width')) * 100;
                }
                if (listener.el.nodeName === 'IMG') {
                    listener.el.style.opacity = 0.3;
                    // listener.el.style.paddingTop = padding + '%';
                }
            }
        }
    },
    filter: {
        progressive (listener, options) {
            if (!listener.src) {
                return;
            }
            const match = /(http|https):\/\/([\w.]+\/?)\S*/;
            const src = !match.test(listener.src)
                ? `https://tlkj-item-pic.oss-cn-beijing.aliyuncs.com${listener.src}`
                : listener.src.replace(
                    'https://tlkj-plusshop.oss-us-west-1.aliyuncs.com',
                    'https://tlkj-plusshop.oss-accelerate.aliyuncs.com'
                );

            // const src = listener.src;
            // listener.src = '';
            listener.src = compressImg(src, listener.el);
        }
    }
});
Vue.component('dynamic', EleFormDynamic);
Vue.component(EleFormUploadFile.name, EleFormUploadFile);
Vue.component(EleFormQuillEdit.name, EleFormQuillEdit);
Vue.component(EleFormCustomSelect.name, EleFormCustomSelect);
Vue.component(EleFormInputWithTips.name, EleFormInputWithTips);
Vue.component(EleFormSelectWithTips.name, EleFormSelectWithTips);
Vue.component(EleFormUploadPlusFile.name, EleFormUploadPlusFile);
Vue.component(EleSpace.name, EleSpace);

// 添加全局方法 $isMobile 和 $toggleMobileMenu
Vue.prototype.$isMobile = function () {
    return this.$store.getters.isMobile;
};

Vue.prototype.$toggleMobileMenu = function () {
    this.$store.dispatch('toggleMobileMenu');
};

// 在创建 Vue 实例前初始化移动设备检测
store.dispatch('checkMobile').then(() => {
    console.log('Main.js: 初始移动设备检测完成，状态:', store.getters.isMobile);
});

Vue.use(ElementUI, { locale });
Vue.use(InfiniteScroll);

new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
});
